package email.becode.simultaneous_interpretation_android.ui

import android.Manifest
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import email.becode.simultaneous_interpretation_android.audio.AudioSource
import email.becode.simultaneous_interpretation_android.translation.TranslationService
import email.becode.simultaneous_interpretation_android.viewmodel.TranslationViewModel

class MainActivity : ComponentActivity() {
    private val viewModel: TranslationViewModel by viewModels()
    
    private val requestPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) { isGranted ->
        if (isGranted) {
            // 权限获取成功,可以开始录音
        } else {
            // 显示错误提示
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // 请求录音权限
        requestPermissionLauncher.launch(Manifest.permission.RECORD_AUDIO)
        
        setContent {
            MaterialTheme {
                MainScreen(viewModel)
            }
        }
    }
}

@Composable
fun MainScreen(viewModel: TranslationViewModel) {
    var selectedTab by remember { mutableStateOf(0) }
    val tabs = listOf("翻译", "历史记录")
    val savedRecords by viewModel.savedRecords.collectAsState(initial = emptyList())

    Column {
        TabRow(selectedTabIndex = selectedTab) {
            tabs.forEachIndexed { index, title ->
                Tab(
                    selected = selectedTab == index,
                    onClick = { selectedTab = index },
                    text = { Text(title) }
                )
            }
        }

        when (selectedTab) {
            0 -> TranslationScreen(viewModel)
            1 -> HistoryScreen(savedRecords)
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TranslationScreen(viewModel: TranslationViewModel) {
    val uiState by viewModel.uiState.collectAsState()
    val savedApiKey by viewModel.savedApiKey.collectAsState(initial = null)
    var showApiKeyDialog by remember { mutableStateOf(savedApiKey == null) }
    var apiKey by remember(savedApiKey) { mutableStateOf(savedApiKey ?: "") }

    // 添加滚动状态
    val sourceListState = rememberLazyListState()
    val translationListState = rememberLazyListState()

    // 自动滚动到底部
    LaunchedEffect(uiState.sourceTexts.size) {
        if (uiState.sourceTexts.isNotEmpty()) {
            sourceListState.animateScrollToItem(uiState.sourceTexts.size - 1)
        }
    }

    LaunchedEffect(uiState.translations.size) {
        if (uiState.translations.isNotEmpty()) {
            translationListState.animateScrollToItem(uiState.translations.size - 1)
        }
    }

    if (showApiKeyDialog) {
        AlertDialog(
            onDismissRequest = { 
                if (savedApiKey != null) {
                    showApiKeyDialog = false
                }
            },
            title = { Text("输入API Key") },
            text = {
                TextField(
                    value = apiKey,
                    onValueChange = { apiKey = it },
                    label = { Text("阿里云API Key") }
                )
            },
            confirmButton = {
                Button(
                    onClick = { 
                        if (apiKey.isNotBlank()) {
                            viewModel.saveApiKey(apiKey)
                            showApiKeyDialog = false
                        }
                    }
                ) {
                    Text("确认")
                }
            }
        )
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        // API Key管理
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text("API Key: ${apiKey.take(8)}...")
            Button(
                onClick = { showApiKeyDialog = true }
            ) {
                Text("修改")
            }
            Button(
                onClick = {
                    viewModel.clearApiKey()
                    apiKey = ""
                    showApiKeyDialog = true
                }
            ) {
                Text("重置")
            }
        }

        Spacer(modifier = Modifier.height(16.dp))

        // 语言选择
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceEvenly
        ) {
            RadioButton(
                selected = uiState.sourceLanguage == TranslationService.LANGUAGE_CHINESE,
                onClick = { viewModel.setSourceLanguage(TranslationService.LANGUAGE_CHINESE) }
            )
            Text("中文")
            
            RadioButton(
                selected = uiState.sourceLanguage == TranslationService.LANGUAGE_ENGLISH,
                onClick = { viewModel.setSourceLanguage(TranslationService.LANGUAGE_ENGLISH) }
            )
            Text("English")
            
            RadioButton(
                selected = uiState.sourceLanguage == TranslationService.LANGUAGE_CANTONESE,
                onClick = { viewModel.setSourceLanguage(TranslationService.LANGUAGE_CANTONESE) }
            )
            Text("粤语")
        }

        Spacer(modifier = Modifier.height(16.dp))

        // 音源选择
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceEvenly
        ) {
            AudioSource.values().forEach { source ->
                Column(
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    RadioButton(
                        selected = uiState.selectedAudioSource == source,
                        onClick = { viewModel.setAudioSource(source) },
                        enabled = !uiState.isRecording
                    )
                    Text(source.toDisplayName())
                }
            }
        }

        Spacer(modifier = Modifier.height(16.dp))

        // 翻译内容显示区域
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .weight(1f)
        ) {
            Column(
                modifier = Modifier.fillMaxSize()
            ) {
                // 源文本列表
                LazyColumn(
                    state = sourceListState,
                    modifier = Modifier
                        .weight(1f)
                        .fillMaxWidth()
                ) {
                    item {
                        Text(
                            text = "源文本:",
                            style = MaterialTheme.typography.titleMedium,
                            modifier = Modifier.padding(vertical = 4.dp)
                        )
                    }
                    items(
                        items = uiState.sourceTexts,
                        key = { text -> text.hashCode() }
                    ) { text ->
                        Text(
                            text = text,
                            modifier = Modifier.padding(vertical = 4.dp)
                        )
                    }
                }

                Divider(modifier = Modifier.padding(vertical = 8.dp))

                // 翻译文本列表
                LazyColumn(
                    state = translationListState,
                    modifier = Modifier
                        .weight(1f)
                        .fillMaxWidth()
                ) {
                    item {
                        Text(
                            text = "翻译文本:",
                            style = MaterialTheme.typography.titleMedium,
                            modifier = Modifier.padding(vertical = 4.dp)
                        )
                    }
                    items(
                        items = uiState.translations,
                        key = { translation -> translation.toString().hashCode() }
                    ) { translation ->
                        Column(
                            modifier = Modifier.padding(vertical = 4.dp)
                        ) {
                            translation.forEach { (language, text) ->
                                Text(
                                    text = when (language) {
                                        TranslationService.LANGUAGE_CHINESE -> "中文: "
                                        TranslationService.LANGUAGE_ENGLISH -> "英文: "
                                        TranslationService.LANGUAGE_CANTONESE -> "粤语: "
                                        else -> "$language: "
                                    } + text,
                                    modifier = Modifier.padding(vertical = 2.dp)
                                )
                            }
                        }
                    }
                }
            }
        }

        // 错误信息显示
        uiState.error?.let { error ->
            Text(
                text = error,
                color = MaterialTheme.colorScheme.error,
                modifier = Modifier.padding(8.dp)
            )
        }

        // 控制按钮
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = 8.dp),
            horizontalArrangement = Arrangement.SpaceEvenly
        ) {
            Button(
                onClick = {
                    if (uiState.isRecording) {
                        viewModel.stopTranslation()
                    } else {
                        viewModel.startTranslation(apiKey)
                    }
                },
                enabled = apiKey.isNotBlank()
            ) {
                Text(if (uiState.isRecording) "停止翻译" else "开始翻译")
            }

            Button(
                onClick = { viewModel.clearTranslations() },
                enabled = !uiState.isRecording
            ) {
                Text("清空")
            }
        }
    }
} 